package cm.util;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.FatalBeanException;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Collection;
import java.util.Objects;

/**
 * 对象拷贝工具
 *
 * @author Jun
 * @date 2022/4/19
 * @time 9:59 下午
 */
public class BeanCopierUtil {

    public static <S, T> void copyList(Collection<S> sCollection, Collection<T> tCollection, Class<T> tClass) {
        if (sCollection == null || tCollection == null || sCollection.size() == 0) {
            return;
        }
        try {
            for (S s : sCollection) {
                T t = tClass.newInstance();
                BeanUtils.copyProperties(s, t);
                tCollection.add(t);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 判断对象属性是否有空值（用于上传校验）
     * @param object
     * @return
     */
    public static boolean checkObjAllFieldsIsNull(Object object){
        return checkObjAllFieldsIsNull(object,null);
    }

    /**
     * 判断对象属性是否有空值（用于上传校验）
     * 排除某个字段
     * @param object
     * @return
     */
    public static boolean checkObjAllFieldsIsNull(Object object,String field){
        if (Objects.isNull(object)){
            return true;
        }
        try {
            for (Field f : object.getClass().getDeclaredFields()){
                if (StrUtil.isNotBlank(field) && StrUtil.equals(f.getName(),field)) continue;
                f.setAccessible(true);
                if (Objects.isNull(f.get(object)) || StrUtil.isBlank(f.get(object).toString())){
                    return true;
                }
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return false;
    }
    /**
     * 功能说明: 只复制source对象的非空属性到target对象空属性上
     * @param source
     * @param target
     * @throws BeansException
     */
    public static void copyNoNullProperties(Object source, Object target) throws BeansException {
        Assert.notNull(source, "Source must not be null");
        Assert.notNull(target, "Target must not be null");
        Class<?> actualEditable = target.getClass();
        PropertyDescriptor[] targetPds = BeanUtils.getPropertyDescriptors(actualEditable);
        for (PropertyDescriptor targetPd : targetPds) {
            if (targetPd.getWriteMethod() != null) {
                PropertyDescriptor sourcePd = BeanUtils.getPropertyDescriptor(source.getClass(), targetPd.getName());
                if (sourcePd != null && sourcePd.getReadMethod() != null) {
                    try {
                        Method sourceReadMethod = sourcePd.getReadMethod();
                        Method targetReadMethod = targetPd.getReadMethod();
                        if (!Modifier.isPublic(sourceReadMethod.getDeclaringClass().getModifiers())) {
                            sourceReadMethod.setAccessible(true);
                        }
                        Object value = sourceReadMethod.invoke(source);
                        if (!Modifier.isPublic(targetReadMethod.getDeclaringClass().getModifiers())) {
                            targetReadMethod.setAccessible(true);
                        }
                        Object targetValue = targetReadMethod.invoke(target);
                        if (Objects.isNull(targetValue) && Objects.nonNull(value)){
                            Method writeMethod = targetPd.getWriteMethod();
                            if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
                                writeMethod.setAccessible(true);
                            }
                            writeMethod.invoke(target, value);
                        }

                    } catch (Throwable ex) {
                        throw new FatalBeanException("Could not copy properties from source to target", ex);
                    }
                }
            }
        }
    }


    /**
     * BeanMerge，对象属性合并(比beanCopy好用)
     * @Author zhengkai.blog.csdn.net
     */
    public static <M> void merge(M target, M destination) throws Exception {
        //获取目标bean
        BeanInfo beanInfo = Introspector.getBeanInfo(target.getClass());
        // 遍历所有属性
        for (PropertyDescriptor descriptor : beanInfo.getPropertyDescriptors()) {
            // 如果是可写属性
            if (descriptor.getWriteMethod() != null) {
                Object defaultValue = descriptor.getReadMethod().invoke(destination);
                //可以使用StringUtil.isNotEmpty(defaultValue)来判断
                if(defaultValue!=null && !"".equals(defaultValue) && defaultValue!="null"){
                    //用非空的defaultValue值覆盖到target去
                    descriptor.getWriteMethod().invoke(target, defaultValue);
                }
            }
        }
    }


}
